<?php
namespace Xinpow\YouApis\Traits;

trait Curl
{
   /**
     * 请求数据
     * 
     * @param $url             请求的url
     * @param array $param     请求的参数
     * @param int $timeout     超时时间
     * @return mixed
     */
    public function request($url, $param = [], $method = 'GET', $header = [])
    {
        $config = require(__DIR__ . '/../config.php');
        $ch = curl_init();
        if(isset($config['debug_key']) && $config['debug_key']) {
            $authorization = $config['debug_key'];
        } else
            $authorization = md5($config['project_key'] . $config['secret_key'] . strtotime(date('Y-m-d H:i'))) . $config['company_id'];

        $header[] = 'x-api-key:' . $authorization;

        if(strtoupper($method) === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        if(strtoupper($method) === 'GET') {
            is_array($param) && $url = $url . '?' . http_build_query($param);
        } else {
            $param = json_encode($param);
            $header[] = 'Content-Type:application/json';
            $header[] = 'Content-Length:' . strlen($param);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $config['base_path'] . trim($url, '/'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']);
        
        $data = curl_exec($ch);
        curl_close($ch);

        return json_decode($data);
    }
}